const log4js = require("log4js");

/**
 * @param {*} req ctx.req
 * @method 获取客户端ip地址
 */
function getClientIp(req) {
  return (
    req.headers["x-forwarded-for"] ||
    req.connection.remoteAddress ||
    req.socket.remoteAddress ||
    req.connection.socket.remoteAddress
  );
}

function isMobile(userAgent) {
  // 判断是移动端还是pc端
  return /Mobile/.test(userAgent) ? "Mobile" : "PC";
}

function formatLog(ctx, message) {
  let client = {
    message: message,
    ip: getClientIp(ctx.req),
    method: ctx.request.method,
    path: ctx.request.path,
    referer: ctx.request.headers["referer"],
    userAgent: isMobile(ctx.request.headers["user-agent"]),
  };
  // 返回客户端信息交给logger打印
  return JSON.stringify(client);
}

// log4js中日志级别
const levels = ["trace", "debug", "info", "warn", "error", "fatal"];
module.exports = (appender, options) => {
  let appenders = {
    cheese: appender, //app.js中配置的appender
  };

  // 如果是开发环境就往appenders添加dev
  if (options.env === "development") {
    appenders.dev = { type: "console" };
  }

  // log4js配置
  log4js.configure({
    appenders: appenders,
    categories: {
      default: {
        //只写了一个默认分类
        appenders: Object.keys(appenders),
        level: options.level, //app.js中设置的level
      },
    },
  });
  const logger = log4js.getLogger();

  return async (ctx, next) => {
    // 在ctx上添加logger的几个方法
    let ctxLogger = {};
    levels.forEach((level) => {
      ctxLogger[level] = (message) => {
        // 格式化日志信息
        logger[level](formatLog(ctx, message));
      };
    });
    ctx.log = ctxLogger;

    await next();
  };
};
